import { TestConfig } from '../common/testConfig.js';
import { getApiData } from '../../network/communicationConverter.js';
import { MeasurementUnit } from '../basicData/measurementUnit.js'
import { CommodityCategory } from '../basicData/commodityCategory.js';
import {
    getCommodityUnit, getCommodityCategory,
    getCustomerData, getTargetObjectDetailInfo,
    getAllTargetObjectPendingReceiveData, getAllTargetObjectPendingPaymentData,
    getSupplierData, getTargetObjectData
} from '../../network/api.js';
import { TestSimulateData } from '../testMgr/testSimulateData.js';
import { CommunicationPageData, ApiReturnStruct, DataPage, NetworkParser } from '../../network/communicationConverter.js';
import { Engine } from '../engine.js';
import { Customer } from '../targetOrg/customer.js';
import { Supplier } from '../targetOrg/supplier.js';
import { Util } from '../../utils/util.js';
import { TargetObjFundingAccount } from '../funds/targetObjFundingAccount.js'
import { Definition } from '../common/definition.js';
import { TargetObject } from '../targetOrg/targetObject.js';
import { FunctionPermissionDefinition } from '../platform/functionPermissionDefinition.js'



export class BasicUiAction {
    ///  获取计量信息
    /// 返回 ApiReturnStruct
    async getCommodityUnit(pageInfo, filterJson = null) {
        if (TestConfig.measurementUnitTest) {

            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));

            /// 模拟数据
            const testSimulateData = new TestSimulateData();

            /// 模拟数据

            let simData = new CommunicationPageData();
            simData.dataList = testSimulateData.createSimMeasurementUnitData();
            simData.pageInfo.total = 100//simData.dataList.length;


            let ret = new ApiReturnStruct();

            ret.data = simData;
            ret.resErr = null;
            return ret;


        } else {
            const apiData = await getApiData(MeasurementUnit.fromJson, 
                Engine.profile.org.orgId, 
                pageInfo, 
                getCommodityUnit,
                filterJson);

            return apiData;
        }
    }

    /// 获取商品类别信息
    /// 返回 ApiReturnStruct

    async getCommodityCategory(pageInfo, filterJson = null) {
        //console.log("----> getCommodityCategory")
        if (TestConfig.commodityKindTest) {
            // 模拟延时
            await new Promise(resolve => setTimeout(resolve, 1000));
            // 模拟数据
            const testSimulateData = new TestSimulateData();
            let simData = new CommunicationPageData();
            simData.dataList = testSimulateData.createSimCommodityCategoryData();
            simData.pageInfo.total = 100;
            let ret = new ApiReturnStruct();
            ret.data = simData;
            ret.resErr = null;
            return ret;
        } else {
            const apiData = await getApiData(
                CommodityCategory.fromJson,
                Engine.profile.org.orgId,
                pageInfo,
                getCommodityCategory,
                filterJson
            );
            return apiData;
        }
    }


    ///  获取客户信息
    async getCustomerData(
        {
            orgId = null,  // 组织ID
            pageInfo = null,  // 分页信息 类型DataPage
            showLoadingPage = true,  // 是否显示加载页面
            filter = null,  // json
        }) {
        if (TestConfig.customerDataTest) {

            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));

            let ret = new ApiReturnStruct();

            let communicationPageData = new CommunicationPageData();
            communicationPageData.pageInfo = pageInfo;
            communicationPageData.dataList = new TestSimulateData().createSimCustomerData();

            ret.data = communicationPageData;
            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId; // 获取当前组织ID 不在默认参数设置，避免TestConfig.warehouseTest 测试时，orgId为空
            let apiData = await getApiData(Customer.fromJson, orgId, pageInfo, getCustomerData, filter, showLoadingPage);
            return apiData;
        }
    }

    /**
 * Get target object data (customers/suppliers)
 * @param {string} orgId - Organization ID
 * @param {DataPage} pageInfo - Pagination information
 * @param {object} [filter] - Filter conditions json data
 * @returns {Promise<ApiReturnStruct>} 
 */
    async getTargetObjectData(
        {
            orgId = null,  // 组织ID
            pageInfo = null,  // 分页信息 类型DataPage
            showLoadingPage = true,  // 是否显示加载页面
            filter = null,  // json
        }
    ) {
        if (TestConfig.customerDataTest || TestConfig.supplierDataTest) {
            // Simulate delay
            await new Promise(resolve => setTimeout(resolve, 1000));

            // Create simulated data
            let simData = new CommunicationPageData();
            simData.pageInfo = pageInfo;

            if (filter != null && filter.customerType === 0) {
                // Customer data only
                simData.dataList = new TestSimulateData().createSimCustomerData();
            } else if (filter != null && filter.state === 1) {
                // Supplier data only (assuming state=1 means suppliers)
                simData.dataList = new TestSimulateData().createSimSupplierData();
            } else {
                // Both customers and suppliers
                let combinedList = [
                    ...new TestSimulateData().createSimCustomerData(),
                    ...new TestSimulateData().createSimSupplierData()
                ];
                simData.dataList = combinedList;
            }

            let ret = new ApiReturnStruct();
            ret.data = simData;
            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;
            return await getApiData(
                TargetObject.fromJson,
                orgId,
                pageInfo,
                getTargetObjectData,
                filter,
                showLoadingPage
            );
        }
    }

    ///  获取供应商信息
    async getSupplierData(
        {
            orgId = null,  // 组织ID
            pageInfo = null,  // 分页信息 类型DataPage
            showLoadingPage = true,  // 是否显示加载页面
            filter = null,  // 过滤条件 json
        }) {
        if (TestConfig.supplierDataTest) {

            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));

            let ret = new ApiReturnStruct();

            let communicationPageData = new CommunicationPageData();
            communicationPageData.pageInfo = pageInfo;
            communicationPageData.dataList = new TestSimulateData().createSimSupplierData();

            ret.data = communicationPageData;
            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId; // 获取当前组织ID 不在默认参数设置，避免TestConfig.warehouseTest 测试时，orgId为空
            let apiData = await getApiData(Supplier.fromJson, orgId, pageInfo, getSupplierData, filter, showLoadingPage);
            return apiData;
        }
    }


    /**
 * Get customer detail information
 * @param {customerId} customerId - 
 * @param {string} [storeId] - Optional store ID
 * @returns {Promise<Customer|null>} Customer detail or null if failed
 */
    async getCustomerDetailInfo(customerId, storeId) {
        storeId = storeId ?? Engine.profile?.filterStore?.id;

        if (TestConfig.customerDataTest) {
            // Return the original customer in test mode
            return (new TestSimulateData().createSimCustomerData())[0];
        } else {
            const res = await getTargetObjectDetailInfo(
                customerId,
                Engine.profile.org.orgId,
                storeId
            );

            // 解析数据，利用 NetworkParser 解析分页数据
            const apiResult = NetworkParser.parseNetworkResult(res, Customer.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    Util.showToast(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /**
* Get supplier detail information
* @param {supplierId} supplierId - 
* @param {string} [storeId] - Optional store ID
* @returns {Promise<Supplier|null>} Supplier detail or null if failed
*/
    async getSupplierDetailInfo(supplierId, storeId) {
        storeId = storeId ?? Engine.profile?.filterStore?.id;

        if (TestConfig.supplierDataTest) {
            // Return the original supplier in test mode
            return (new TestSimulateData().createSimSupplierData())[0];
        } else {
            const res = await getTargetObjectDetailInfo(
                supplierId,
                Engine.profile.org.orgId,
                storeId
            );

            // 解析数据，利用 NetworkParser 解析分页数据
            const apiResult = NetworkParser.parseNetworkResult(res, Supplier.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    Util.showToast(apiResult.resErr);
                }
                return null;
            }
        }
    }


    /// 刷新客户应收总额信息
    /// 返回类型： CommunicationPageData
    /// pendingReceiveOrderfilter 类型：PendingReceiveOrderFilter
    async getPendingReceiveData(pendingReceiveOrderfilter) {
        if (!pendingReceiveOrderfilter || Util.isEmpty(pendingReceiveOrderfilter.customerId))
            return;

        const apiData = await getApiData(
            TargetObjFundingAccount.fromJson,
            Engine.profile.org.orgId,
            new DataPage(0, 0, Definition.gDefualPageSize),
            getAllTargetObjectPendingReceiveData,
            pendingReceiveOrderfilter.toJson()
        );

        if (apiData.data != null) {
            // 显示基本单位页面
            const comData = apiData.data;
            return comData;
        } else {
            if (apiData.resErr != null) {
                Util.showToast("获取资金账户信息失败：" + apiData.resErr);
            }

            return null;
        }
    }

    /// 刷新客户应付总额信息
    // pendingPaymentOrderFilter 类型：PendingPaymentOrderFilter
    async getPendingPaymentData(pendingPaymentOrderFilter) {
        if (!pendingPaymentOrderFilter || Util.isEmpty(pendingPaymentOrderFilter.targetObjId))
            return;

        const apiData = await getApiData(
            TargetObjFundingAccount.fromJson,
            Engine.profile.org.orgId,
            new DataPage(0, 0, Definition.gDefualPageSize),
            getAllTargetObjectPendingPaymentData,
            pendingPaymentOrderFilter.toJson()
        );

        if (apiData.data != null) {
            // 显示基本单位页面
            const comData = apiData.data;
            return comData;
        } else {
            if (apiData.resErr != null) {
                Util.showToast("获取资金账户信息失败：" + apiData.resErr);
            }

            return null;
        }
    }
    /// 客户详情
    async showCustomerDetailPage(customerId, editMode) {

        editMode = editMode == true;

        if (!Util.isEmpty(customerId)) {
            uni.navigateTo({
                url: '/pages/partners/customerDetailPage?customerId=' + customerId + '&editMode=' + editMode
            })
        } else {
            uni.navigateTo({
                url: '/pages/partners/customerDetailPage?editMode=true'
            })
        }
    }

    /// 供应商详情
    async showSupplierDetailPage(supplierId, editMode) {

        editMode = editMode == true;

        if (!Util.isEmpty(supplierId)) {
            uni.navigateTo({
                url: '/pages/partners/supplierDetailPage?supplierId=' + supplierId + '&editMode=' + editMode
            })
        } else {
            uni.navigateTo({
                url: '/pages/partners/supplierDetailPage?editMode=true'
            })
        }
    }

    /// 显示组织对象页面
    // type TargetObjectType
    // curTargetObj  TargetObject
    // filter TargetObjectFilter
    async showTargetObjectMgrPage({ selectionMode = true, type = null, curTargetObj = null, filter = null } = {}) {
        let supplierAccessable = false;
        if (Engine.profile?.permissionMgr.hasPermission([
            FunctionPermissionDefinition.P_Supplier_Read,
            FunctionPermissionDefinition.P_Supplier_Edit
        ])) {
            supplierAccessable = true;
        }


        let customerAccessable = false;
        if (Engine.profile?.permissionMgr.hasPermission([
            FunctionPermissionDefinition.P_Customer_Read,
            FunctionPermissionDefinition.P_Customer_Edit
        ])) {
            customerAccessable = true;
        }

        if (TestConfig.supplierDataTest) {
            supplierAccessable = true;
        }

        if (TestConfig.customerDataTest) {
            customerAccessable = true;
        }



        var ret;

        if (customerAccessable && supplierAccessable) {
            let curTargetObjParam = curTargetObj == null ? "" : "&curPartner=" + encodeURIComponent(JSON.stringify(curTargetObj.toCopyJson()));
            let filterParam = filter == null ? "" : "&filter=" + encodeURIComponent(JSON.stringify(filter.toJson()));
            let typeParm = type == null ? "" : "&type=" + TargetObjectType.code;
            uni.navigateTo({
                url: '/pages/partners/partnerMgrPage?selectionMode=' + selectionMode + typeParm + curTargetObjParam + filterParam
            })
        }
        else if (supplierAccessable) {
            let curSupplier = curTargetObj == null ? "" : "&curSupplier=" + encodeURIComponent(JSON.stringify(curTargetObj.toCopyJson()));
            let filterParam = filter == null ? "" : "&filter=" + encodeURIComponent(JSON.stringify(filter.toJson()));
            uni.navigateTo({
                url: '/pages/partners/supplierMgrPage?selectionMode=' + selectionMode + curSupplier + filterParam
            })
        }
        else if (customerAccessable) {
            let curCustomer = curTargetObj == null ? "" : "&curCustomer=" + encodeURIComponent(JSON.stringify(curTargetObj.toCopyJson()));
            let filterParam = filter == null ? "" : "&filter=" + encodeURIComponent(JSON.stringify(filter.toJson()));
            uni.navigateTo({
                url: '/pages/partners/supplierMgrPage?selectionMode=' + selectionMode + curCustomer + filterParam
            })
        }
        else {
            Util.showToast("权限不足,无法选择供应商或客户!");
        }

        return ret;

    }



}
